package jp.co.apl.haven_enquete.android.worker;

import java.util.List;

import jp.co.apl.haven.generated.HavenProtos.Answer;
import jp.co.apl.haven.generated.HavenProtos.AnswerList;
import jp.dev7.android.worker.Worker;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.AllClientPNames;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import android.os.Bundle;
import android.os.Message;

public class AnswerUploadWorker extends Worker<Boolean> {

    private List<Answer> answers;

    public AnswerUploadWorker(List<Answer> answers) {
        super();
        this.answers = answers;
    }

    @Override
    protected Boolean doInBackground() throws Exception {

        AnswerList answerList =
            AnswerList.newBuilder().addAllAnswer(answers).build();

        HttpParams params = new BasicHttpParams();
        {
            params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
            params.setIntParameter(AllClientPNames.SO_TIMEOUT, 30000);
        }
        HttpClient client = new DefaultHttpClient(params);

        HttpPost request =
            new HttpPost("http://10.0.2.2:8080/haven-web/upload/");
        HttpEntity entity = new ByteArrayEntity(answerList.toByteArray());
        request.setEntity(entity);

        if (isCanceled()) {
            return true;
        }

        HttpResponse response = client.execute(request);

        if (isCanceled()) {
            return true;
        }

        return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    }

    @Override
    protected Message done() {
        Message msg = new Message();
        Bundle data = new Bundle();

        Boolean result = getResult();
        if (result == null) {
            result = false;
        }
        data.putBoolean(RESULT, result);

        msg.setData(data);
        return msg;
    }

}
